package com.example.remoteaction.extension.demo.server;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.LazyInitializationException;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.transaction.annotation.Transactional;

import com.example.remoteaction.extension.demo.client.GreetingService;
import com.example.remoteaction.extension.demo.domain.School;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */

@Configurable(autowire=Autowire.BY_TYPE)
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {
	@PersistenceContext    
    transient EntityManager entityManager;    
	
	@Override
	@Transactional
	public School getSchool(boolean fetchStudent) {
		
		
		String query = "select o from School o";
		if(fetchStudent){
			query+=" join fetch o.studentList";
		}
		//return the 1st school
		return (School) entityManager.createQuery(query).getResultList().get(0);

	}
	
	@Transactional
	public List<School> getAllSchool(boolean fetchStudent) {
		
		
		String query = "select distinct(o) from School o";
		if(fetchStudent){
			query+=" join fetch o.studentList";
		}
		
		return (List<School>) entityManager.createQuery(query).getResultList();

	}
	
	@Transactional
	public String saveSchool(List<School> schoolList){
		System.out.println("-------------- Server Received -----------------");
		for(School school : schoolList){
			System.out.println("School Name: "+school.getSchoolName());
			try{
				
				System.out.println("number of students: "+school.getStudentList().size()+"\n"
				+"student list class:"+ school.getStudentList().getClass());
				
			}catch(LazyInitializationException e){
				System.out.println("student LAZY list: "+ school.getStudentList().getClass());
			}
			
		}
		System.out.println("-------------------------------------------------");
		
		return "server received "+schoolList.size() + " schools, please check log for more details";
		
	}
	
}
